package com.igeek.collateral.controller;



import com.igeek.collateral.entity.Collateral;
import com.igeek.collateral.entity.Contract;
import com.igeek.collateral.mapper.ContractMapper;
import com.igeek.collateral.result.Result;
import com.igeek.collateral.service.ContractService;
import com.igeek.collateral.service.ICollateralService;
import com.igeek.collateral.service.Impl.OssService;
import com.igeek.collateral.utils.WordUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin/contract")
@Slf4j
@Api(tags = "合同接口")
public class ContractController {

    @Autowired
    private ContractService contractService;
    @Autowired
    private ICollateralService collateralService;
    @Autowired
    private ContractMapper contractMapper;

    @GetMapping("/getContractList")
    public Result getContractList(){
        List<Contract> list = contractService.list();
        if (list.size() >0) {
            return new Result(true, "查询成功", list);
        }
        return new Result(false, "查询失败");
    }
    //根据ID能获取押品信息
    @GetMapping("/getCollateralById/{id}")
    public Result getCollateralById(@PathVariable("id") Integer id){
      Collateral collateral =collateralService.getById(id);
        if(collateral != null){
            return new Result(true, "查询成功",collateral);
        }
        return new Result(false, "查询失败");
    }
    @GetMapping( "getContractById/{id}")
    public Result getContractById(@PathVariable("id") Integer id){
        Contract contract = contractService.getById(id);
        return new Result(true, "查询成功",contract);

    }

    @PostMapping("/addContract")
    public Result add(@RequestBody Contract contract) throws Exception {

            String filePath = WordUtils.createWord(contract);
            contract.setFilePath(filePath);
            contract.setServicePeriod(contract.getServicePeriod());
            contract.setContractName(contract.getContractName());
            contract.setCreatedTime(new Date());
            contract.setPartyB(contract.getPartyB());
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName() , ContentType.APPLICATION_ATOM_XML.toString() ,fis);
            String url = OssService.upload(multipartFile);
            contract.setFilePath(url);
            contractService.save(contract);
            return new Result(true , "添加成功");
        }



    //下载模板
    @ApiOperation("下载合同模板")
    @GetMapping("/download")
    public void download(HttpServletResponse response){
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:template/项目合同协议书.docx");
        } catch (FileNotFoundException e) {
            log.warn("模板文件未找到~");
            return;
        }

        if(file!=null && file.isFile()){
            String fileName = file.getName();

            response.reset();
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            //边读边写
            try (
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            ){
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len=bis.read(bytes))!=-1){
                    bos.write(bytes , 0 , len);
                    bos.flush();
                }
            } catch (IOException e) {
                log.error("模板文件下载失败，理由：{}~" , e.getMessage());
            }
        }

    }
    //上传合同文件
//    @ApiOperation("上传合同文件")
//    @PostMapping("/upload")
//    public Result upload(MultipartFile excelFile) throws IOException {
//        boolean flag = contractService.upload(excelFile);
//        if(flag){
//            return new Result(true , "上传成功");
//        }
//        return new Result(false ,"上传失败");
//    }





}




